package cn.tedu.barrage;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.VideoView;

import java.util.Random;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.Danmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;

public class MainActivity extends AppCompatActivity {
    private VideoView videoView;
    private LinearLayout sendLayout;
    private Button sendButton;
    private EditText editText;
    private DanmakuView danmakuView;

    private boolean showDanmaku;//显示弹幕
    private DanmakuContext danmakuContext;//弹幕上下文

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDanmaku();
        playVideo();
    }

    /**
     * 初始化界面控件
     */
    private void initView(){
        videoView = (VideoView)findViewById(R.id.videoview);
        sendLayout = (LinearLayout)findViewById(R.id.layout_send);
        sendButton = (Button)findViewById(R.id.btn_send);
        editText = (EditText)findViewById(R.id.et_text);
        danmakuView = (DanmakuView)findViewById(R.id.danmaku);
    }
    /**
     * 播放视频
     */
    private void playVideo(){
        //获取视频url
        String url = "android.resource://"+getPackageName()+"/"+R.raw.sun;
        if(url != null){
            //加载视频
            videoView.setVideoURI(Uri.parse(url));
            //播放视频
            videoView.start();
        } else {
            //将背景设置为透明
            videoView.getBackground().setAlpha(0);
        }
    }


    /**
     * 创建弹幕解析器
     */
    private BaseDanmakuParser parser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };
    /**
     * 初始化弹幕
     */
    private void initDanmaku(){
        //设置回调函数
        danmakuView.setCallback(new DrawHandler.Callback() {
            @Override
            public void prepared() {
                showDanmaku = true;
                //开始弹幕
                danmakuView.start();
                //随机生成弹幕
                generateDanmakus();
            }

            @Override
            public void updateTimer(DanmakuTimer timer) {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {

            }

            @Override
            public void drawingFinished() {

            }
        });
        //新建一个DamakuContext对象，弹幕上下文
        danmakuContext = DanmakuContext.create();
        //提升屏幕绘制效率
        danmakuView.enableDanmakuDrawingCache(true);
        //进行弹幕准备，弹幕解析器和上下文
        danmakuView.prepare(parser,danmakuContext);
        //为danmakuView设置点击事件，点击屏幕的时候显示/隐藏发送弹幕布局部分
        danmakuView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果现在是隐藏发送布局，当点击后，出现弹幕布局
                if (sendLayout.getVisibility() == View.GONE){
                    //显示布局
                    sendLayout.setVisibility(View.VISIBLE);
                } else {
                    //隐藏布局
                    sendLayout.setVisibility(View.GONE);
                }
            }
        });
        //为发送按钮设置点击事件
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取输入框内的文字
                String context = editText.getText().toString();
                //判断是否有文字
                if (!TextUtils.isEmpty(context)){
                    //添加一条弹幕
                    addDanmaku(context,true);
                    //清空输入框
                    editText.setText("");
                }
            }
        });
    }

    /**
     * 添加弹幕
     * @param context 弹幕的具体内容
     * @param border 弹幕是否有边框
     */
    private void addDanmaku(String context,boolean border){
        //创建弹幕对象
        // TYPE_SCROLL_RL，从右向左滚动的弹幕
        // TYPE_SCROLL_LR，从左向右滚动的弹幕
        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(
                BaseDanmaku.TYPE_SCROLL_RL
        );
        //设置弹幕内容
        danmaku.text = context;
        //设置内边距(像素)
        danmaku.padding = 6;
        //设置弹幕字号
        danmaku.textSize = 30;
        //设置弹幕字颜色
        danmaku.textColor = Color.WHITE;
        //设置弹幕时间
        danmaku.setTime(danmakuView.getCurrentTime());
        if (border){
            //如果存在边框，设置边框颜色为蓝色
            danmaku.borderColor = Color.BLUE;
        }
        //添加弹幕
        danmakuView.addDanmaku(danmaku);

    }

    /**
     * 随机生成弹幕
     */
    private void generateDanmakus(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (showDanmaku){
                    int num = new Random().nextInt(300);
                    String content = ""+num;
                    addDanmaku(content,false);
                    try {
                        Thread.sleep(num);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 隐藏软键盘
     * @param ev
     * @return
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //获取当前获得焦点的View
                View view = getCurrentFocus();
                //调用方法判断是否需要隐藏键盘
                KeyboardUtils.hideKeyboard(ev, view, this);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (danmakuView != null && danmakuView.isPrepared()) {
            danmakuView.pause();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (danmakuView != null && danmakuView.isPrepared() &&
                danmakuView.isPaused()) {
            danmakuView.resume();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        showDanmaku = false;
        if (danmakuView != null) {
            danmakuView.release();
            danmakuView = null;
        }
    }
}